<template>
  <div class="payment-container">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">💰 支付管理</span>
          <el-button type="primary" @click="fetchPayments">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <!-- 搜索筛选区域 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline class="filter-form">
          <el-form-item label="支付状态">
            <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
              <el-option label="未支付" :value="0" />
              <el-option label="支付成功" :value="1" />
              <el-option label="支付失败" :value="2" />
              <el-option label="已退款" :value="3" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="支付方式">
            <el-select v-model="filterForm.payment_method" placeholder="选择支付方式" clearable>
              <el-option label="微信支付" value="wechat" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="银联支付" value="unionpay" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          
          <el-form-item label="搜索">
            <el-input
              v-model="filterForm.search"
              placeholder="支付单号/订单号"
              style="width: 200px"
              clearable
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilters">
              <el-icon><RefreshRight /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 按订单号分组的支付记录 -->
      <div class="payment-groups">
        <div 
          v-for="group in groupedPayments" 
          :key="group.order_no"
          class="payment-group"
        >
          <el-card class="group-card">
            <!-- 订单信息头部 -->
            <div class="order-header">
              <div class="order-info">
                <div class="order-main">
                  <span class="order-no">{{ group.order_no }}</span>
                  <el-tag 
                    v-if="group.activity_id" 
                    type="primary" 
                    size="small"
                    class="activity-tag"
                  >
                    #{{ group.activity_id }} {{ group.activity_title || '未知活动' }}
                  </el-tag>
                  <el-tag v-else type="info" size="small">无关联活动</el-tag>
                </div>
                <div class="order-details">
                  <span class="user-name">👤 {{ group.user_name }}</span>
                  <span class="venue-name">🏢 {{ group.venue_name }}</span>
                  <span class="payment-count">📋 {{ group.payments.length }}次支付记录</span>
                </div>
              </div>

              <!-- 右侧状态和操作区域 -->
              <div class="order-actions">
                <div class="final-status">
                  <span class="status-label">最终状态：</span>
                  <el-tag :type="getStatusType(group.finalStatus)">
                    {{ group.finalStatusText }}
                  </el-tag>
                </div>
                <div class="total-amount">
                  <span class="amount-label">总金额：</span>
                  <span class="amount">¥{{ group.totalAmount.toFixed(2) }}</span>
                </div>
              </div>
            </div>

            <!-- 展开的支付记录列表 -->
            <el-collapse-transition>
              <div v-show="expandedGroups.includes(group.order_no)" class="payment-list">
                <el-divider content-position="left">支付记录详情</el-divider>
                <el-table :data="group.payments" stripe size="small">
                  <el-table-column prop="payment_no" label="支付单号" width="180" />
                  
                  <el-table-column prop="amount" label="金额" width="100">
                    <template #default="{ row }">
                      <span class="amount">¥{{ row.amount.toFixed(2) }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column label="支付方式" width="100">
                    <template #default="{ row }">
                      <el-tag v-if="row.payment_method === 'wechat'" type="success" size="small">
                        微信支付
                      </el-tag>
                      <el-tag v-else-if="row.payment_method === 'alipay'" type="primary" size="small">
                        支付宝
                      </el-tag>
                      <el-tag v-else-if="row.payment_method === 'unionpay'" type="warning" size="small">
                        银联支付
                      </el-tag>
                    </template>
                  </el-table-column>

                  <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                      <el-tag :type="getStatusType(row.status)" size="small">
                        {{ row.status_text }}
                      </el-tag>
                    </template>
                  </el-table-column>

                  <el-table-column prop="paid_at" label="支付时间" width="160" />

                  <el-table-column prop="created_at" label="创建时间" width="160" />

                  <el-table-column prop="transaction_id" label="交易流水号" width="160" />
                </el-table>
              </div>
            </el-collapse-transition>
          </el-card>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="支付详情" 
      width="600px"
    >
      <el-descriptions :column="2" border v-if="currentPayment">
        <el-descriptions-item label="支付ID">{{ currentPayment.id }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ currentPayment.order_no }}</el-descriptions-item>
        <el-descriptions-item label="支付金额">¥{{ currentPayment.amount.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentMethodText(currentPayment.payment_method) }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">{{ getStatusText(currentPayment.status) }}</el-descriptions-item>
        <el-descriptions-item label="交易流水号">{{ currentPayment.transaction_id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ currentPayment.paid_at || '-' }}</el-descriptions-item>
        <el-descriptions-item label="用户手机">{{ currentPayment.user_phone || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 支付日志对话框 -->
    <el-dialog 
      v-model="logsDialogVisible" 
      title="支付日志" 
      width="800px"
    >
      <div class="logs-container">
        <el-timeline>
          <el-timeline-item
            v-for="log in paymentLogs"
            :key="log.id"
            :timestamp="log.created_at"
            placement="top"
          >
            <div class="log-item">
              <div class="log-action">{{ log.action }}</div>
              <div class="log-message">{{ log.message }}</div>
              <div class="log-data" v-if="log.data">
                <pre>{{ JSON.stringify(JSON.parse(log.data), null, 2) }}</pre>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, 
  Search, 
  RefreshRight, 
  Plus, 
  Minus 
} from '@element-plus/icons-vue'
import { getPaymentRecords } from '@/api/payment'

// 响应式数据
const loading = ref(false)
const payments = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const expandedGroups = ref([])

// 对话框状态
const detailDialogVisible = ref(false)
const logsDialogVisible = ref(false)
const currentPayment = ref(null)
const paymentLogs = ref([])
const dateRange = ref([])

// 筛选表单
const filterForm = reactive({
  status: null,
  payment_method: '',
  start_date: '',
  end_date: '',
  search: ''
})

// 按订单号分组的支付记录
const groupedPayments = computed(() => {
  const groups = {}
  
  payments.value.forEach(payment => {
    const orderNo = payment.order_no
    if (!groups[orderNo]) {
      groups[orderNo] = {
        order_no: orderNo,
        user_name: payment.user_name,
        venue_name: payment.venue_name,
        activity_id: payment.activity_id,
        activity_title: payment.activity_title,
        payments: []
      }
    }
    groups[orderNo].payments.push(payment)
  })
  
  // 计算每个订单组的最终状态和总金额
  Object.values(groups).forEach(group => {
    // 计算总金额
    group.totalAmount = group.payments.reduce((sum, payment) => sum + payment.amount, 0)
    
    // 计算最终状态：优先级：支付成功 > 支付失败 > 已退款 > 未支付
    const statuses = group.payments.map(p => p.status)
    if (statuses.includes(1)) {
      group.finalStatus = 1
      group.finalStatusText = '支付成功'
    } else if (statuses.includes(2)) {
      group.finalStatus = 2
      group.finalStatusText = '支付失败'
    } else if (statuses.includes(3)) {
      group.finalStatus = 3
      group.finalStatusText = '已退款'
    } else {
      group.finalStatus = 0
      group.finalStatusText = '未支付'
    }
  })
  
  return Object.values(groups)
})

// 获取支付记录
const fetchPayments = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      per_page: pageSize.value,
      ...filterForm
    }
    
    const response = await getPaymentRecords(params)
    payments.value = response.data.payments || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('获取支付记录失败')
  } finally {
    loading.value = false
  }
}

// 切换分组展开状态
const toggleGroup = (orderNo) => {
  const index = expandedGroups.value.indexOf(orderNo)
  if (index > -1) {
    expandedGroups.value.splice(index, 1)
  } else {
    expandedGroups.value.push(orderNo)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 未支付
    1: 'success',  // 支付成功
    2: 'danger',   // 支付失败
    3: 'info'      // 已退款
  }
  return statusMap[status] || 'info'
}

// 查看订单详情（显示整个订单组）
const viewOrderDetail = (group) => {
  // 显示最新的支付记录作为代表
  const latestPayment = group.payments[0] // 已经按创建时间倒序排列
  currentPayment.value = {
    ...latestPayment,
    // 添加订单组信息
    total_amount: group.totalAmount,
    final_status: group.finalStatus,
    final_status_text: group.finalStatusText,
    payment_count: group.payments.length
  }
  detailDialogVisible.value = true
}

// 查看订单日志（显示整个订单的所有支付记录）
const viewOrderLogs = async (group) => {
  try {
    // 生成所有支付记录的日志
    paymentLogs.value = []
    group.payments.forEach((payment, index) => {
      paymentLogs.value.push({
        id: `${payment.id}_create`,
        action: `创建支付 #${index + 1}`,
        message: `支付订单创建成功，金额：¥${payment.amount.toFixed(2)}`,
        created_at: payment.created_at,
        data: JSON.stringify({
          payment_no: payment.payment_no,
          amount: payment.amount,
          payment_method: payment.payment_method
        })
      })
      
      if (payment.paid_at) {
        paymentLogs.value.push({
          id: `${payment.id}_paid`,
          action: `支付完成 #${index + 1}`,
          message: `支付成功，交易流水号：${payment.transaction_id || '无'}`,
          created_at: payment.paid_at,
          data: JSON.stringify({
            payment_no: payment.payment_no,
            transaction_id: payment.transaction_id,
            status: payment.status_text
          })
        })
      }
    })
    
    // 按时间排序
    paymentLogs.value.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
    logsDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取支付日志失败')
  }
}

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    filterForm.start_date = dates[0]
    filterForm.end_date = dates[1]
  } else {
    filterForm.start_date = ''
    filterForm.end_date = ''
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPayments()
}

// 重置筛选
const resetFilters = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = key === 'status' ? null : ''
  })
  dateRange.value = []
  currentPage.value = 1
  fetchPayments()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPayments()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchPayments()
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const map = {
    wechat: '微信支付',
    alipay: '支付宝',
    unionpay: '银联支付'
  }
  return map[method] || method
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: '未支付',
    1: '支付成功',
    2: '支付失败',
    3: '已退款'
  }
  return map[status] || status
}

// 页面加载时获取数据
onMounted(() => {
  fetchPayments()
})
</script>

<style scoped>
.payment-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: var(--text-primary);
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  background: var(--bg-secondary);
  padding: 20px;
  border-radius: 8px;
}

.payment-groups {
  margin-bottom: 20px;
}

.payment-group {
  margin-bottom: 16px;
}

.group-card {
  border: 1px solid var(--border-color);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-main {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-no {
  font-size: 16px;
  font-weight: bold;
  color: var(--color-primary);
}

.activity-tag {
  max-width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.order-details {
  display: flex;
  align-items: center;
  gap: 20px;
  font-size: 14px;
  color: var(--text-secondary);
}

.order-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-end;
  min-width: 280px;
}

.final-status, .total-amount {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-label, .amount-label {
  font-size: 13px;
  color: var(--text-secondary);
  font-weight: 500;
}

.amount {
  font-weight: bold;
  color: var(--color-success);
  font-size: 16px;
}

.total-amount .amount {
  font-size: 18px;
  color: #e74c3c;
}

.payment-list {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--border-color);
}

.payment-list .amount {
  font-weight: bold;
  color: var(--color-success);
}

.total-amount {
  font-weight: bold;
  font-size: 14px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.payment-detail {
  margin-bottom: 20px;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
}

.log-item {
  padding: 8px 0;
}

.log-action {
  font-weight: bold;
  color: var(--color-primary);
  margin-bottom: 4px;
}

.log-message {
  color: var(--text-primary);
  margin-bottom: 8px;
}

.log-data {
  background-color: var(--bg-secondary);
  padding: 8px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  overflow-x: auto;
}

.log-data pre {
  margin: 0;
  white-space: pre-wrap;
}
</style> 